<template>
  <!-- 添加请款单-->
  <a-modal :width="1200" v-model:visible="showAddBill" top="8vh" :title="`添加请款单-货款${settleType === 1 ? '现结' : '月结'}`" :ok-loading="submitLoading" title-align="start" :mask-closable="false" @cancel="closedDialog" :on-before-ok="submitData">
    <div class="pay-list-w">
      <template v-for="item in payList" :key="item.supplierId">
        <AddPayrollRequisitionItem ref="myComponentRefs" :supplierAccounts="supplierAccounts[item.supplierId]" :userList="userList" :detail="item" />
      </template>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getSupplierInfo, createPaymentOrder } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import useUserStore from '@/store/modules/user'
  import AddPayrollRequisitionItem from './addPayrollRequisitionItem.vue'

  onMounted(() => {
    getUserList()
    setDefaultList()
  })

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [],
    },
    settleType: {
      type: Number,
      default: 1,
    },
  })

  const myComponentRefs = ref([])
  const showAddBill = ref(props.isShow)
  const submitLoading = ref(false)
  const useBaseData = useBaseDataStore()
  const payList = ref<Array<any>>([])
  const userList = ref<Array<any>>([])
  const userStore = useUserStore()
  const supplierAccounts = ref<any>({})

  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList
  }
  // 初始化数据
  function setDefaultList() {
    //根据供应商合并
    let payListMap: any = []
    props.list?.forEach((el: any) => {
      if (!payListMap[el.supplierId]) {
        payListMap[el.supplierId] = {
          supplierId: el.supplierId,
          supplierName: el.supplierName,
          supplierCode: el.supplierCode,
          settleType: props.settleType,
          user: {
            id: userStore.userId,
            userName: userStore.userName,
          },
          supplierAccounts: [],
          orderPoolParams: [],
        }
      }
      payListMap[el.supplierId].orderPoolParams.push(el)
    })
    payList.value = Object.values(payListMap)
    payList.value.forEach((item: any) => {
      getSuppilerInfo(item.supplierId)
    })
  }
  // 获取供应商收款方信息列表
  async function getSuppilerInfo(key: string) {
    const res: any = await getSupplierInfo({ id: key })
    if (res) {
      supplierAccounts.value[key] = res?.data?.supplierAccounts || []
    }
  }

  async function validInfo() {
    for (let i in payList.value) {
      let el = myComponentRefs.value[i]
      let valid = await el?.validateData()
      if (!valid) return false
    }
    return true
  }

  // 确认
  async function submitData() {
    let valid = await validInfo()
    if (!valid) return false
    let orderCreateParams: Array<any> = []
    payList.value.forEach((item: any, i: number) => {
      let el = myComponentRefs.value[i]
      let detailInfo = el?.detailInfo || {}
      orderCreateParams.push({
        gmtExpectedPayment: detailInfo.gmtExpectedPayment,
        account: detailInfo.payeeInfo?.account,
        bank: detailInfo.payeeInfo?.bank,
        payee: detailInfo.payeeInfo?.payee,
        type: detailInfo.payeeInfo?.type,
        requestUid: detailInfo.user?.id,
        requestUname: detailInfo.user?.userName,
        settleType: detailInfo.settleType,
        supplierAccountId: detailInfo.payeeInfo?.id,
        supplierId: detailInfo.supplierId,
        supplierName: detailInfo.supplierName,
        supplierCode: detailInfo.supplierCode,
        urgentStatus: detailInfo.urgentStatus,
        attachment: detailInfo.attachment,
        remark: detailInfo.remark,
        orderPoolParams: detailInfo.orderPoolParams?.map((el: any) => {
          return {
            paymentPoolId: el.id,
            requestAmount: el.requestPrice,
          }
        }),
      })
    })
    const res = await createPaymentOrder({ orderCreateParams })
    if (!res) return false
    Message.success('添加成功')
    emit('success')
    closedDialog()
  }
  // 关闭
  function closedDialog() {
    showAddBill.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .pay-list-w {
    height: calc(84vh - 160px);
    overflow-x: hidden;
    overflow-y: auto;
  }
  .pay-item {
    border: 1px solid #ddd;
    margin-bottom: 10px;
    padding: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .payeeInfo {
    font-size: 12px;
    margin-left: 10px;
    .label {
      color: #999;
    }
  }
  .total-w {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 10px;
    p {
      font-weight: bold;
      text-align: right;
      margin-left: 30px;
    }
    .label {
      color: #999;
      font-weight: normal;
    }
  }
</style>
